package com.wuye.web;

import java.util.HashSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LangUtil {

    public static <E> HashSet<E> toHashSet(E[] bs) {
        HashSet<E> set = new HashSet<E>();
        for (E o : bs)
            set.add(o);
        return set;
    }

    public static boolean isNum(String str) {
        return str != null && str.matches("[-]{0,1}\\d+");
    }

    public static boolean isNum16(String str) {
        return str != null && str.toLowerCase().matches("[-]{0,1}[0-9a-f]+");
    }

    public static String reg(String body, String reg, int group) {
        Pattern pat = Pattern.compile(reg);
        Matcher match = pat.matcher(body);
        if (match.find()) {
            return match.group(group);
        }
        return null;
    }

    public static String substring(String body, String start, String end) {
        int startIndex = body.indexOf(start);
        if (startIndex >= 0) {
            String str = body.substring(startIndex);
            int endIndex = str.indexOf(end);
            if (endIndex > 0) {
                return str.substring(0, endIndex);
            }
        }
        return null;
    }

    public static String replaceTag(String html, String begReg, String endFlag,
                                    boolean includeEndTag) {
        Pattern bReg = Pattern.compile("<[^>]*" + begReg + "[^>]*>");
        Matcher match = bReg.matcher(html);
        if (match.find()) {
            String left = html.substring(match.start());
            int end = left.indexOf(endFlag);
            if (end > 0) {
                return html.substring(0, match.start())
                        + left.substring(end
                        + (includeEndTag ? endFlag.length() : 0));
            }
        }
        return html;
    }

    public static String getVal(String[] json, String key, String defaultVal) {
        for (int i = 0; i < json.length - 1; i++) {
            if (json[i].equals(key)) {
                return json[i + 1];
            }
        }
        return defaultVal;
    }
}
